<template>
  <div id="container">
    <div id="header">
      <div class="logo">
        <img src="../assets/img/nepmLogo.gif" alt="logo" />
      </div>
      <div class="title">
        <div class="h1">环保公众监督系统</div>
      </div>
      <div class="link">
        <el-button class="plain-button" text @click="toLogin" style="color: rgb(99 184 255) !important" link>登录</el-button>
      </div>
    </div>
    <div id="body">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <h1 class="info">账户信息</h1>
          </div>
        </template>
        <div class="registerwin">
          <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="120px" :size="formSize" status-icon>
            <div class="registerform">
              <el-form-item label="用户名" prop="name">
                <el-input v-model="form.name" class="input" placeholder="请输入用户名" />
              </el-form-item>
              <el-form-item label="手机号码" prop="telephone">
                <el-input v-model="form.telephone" class="input" placeholder="请输入11位手机号" />
              </el-form-item>
              <el-form-item label="选择出生日期">
                <el-col :span="13">
                  <el-date-picker v-model="form.birthDay" type="date" placeholder="Pick a date" style="width: 100%" />
                </el-col>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex">
                  <el-radio label="0">男</el-radio>
                  <el-radio label="1">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="身份" prop="sex">
                <el-radio-group v-model="form.userType">
                  <el-radio label="3">监督员</el-radio>
                  <el-radio label="2">网格员</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="form.password" placeholder="请输入密码" class="input" />
              </el-form-item>
              <el-form-item label="确认密码" prop="checkPass">
                <el-input type="password" v-model="form.checkPass" placeholder="确认密码" class="input" />
              </el-form-item>
              <el-form-item label="验证码" prop="verifyCode">
                <div class="captcha-container">
                  <el-input v-model="form.verifyCode" placeholder="输入验证码" class="input small-input" />
                  <div class="canvas-box">
                    <canvas
                      id="id-canvas"
                      class="id-canvas"
                      :width="props.contentWidth"
                      :height="props.contentHeight"
                      @click="refreshCaptcha"
                    ></canvas>
                  </div>
                </div>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="onSubmit(ruleFormRef)">注册</el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeUnmount, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import $axios from '../components/utils/axios'
import { ElMessage } from 'element-plus'

const router = useRouter()

const toLogin = () => {
  router.push('/login')
}

const formSize = ref('default')
const ruleFormRef = ref()

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入确认密码！'))
  } else if (value !== form.value.password) {
    callback(new Error('确认密码与密码不匹配！'))
  } else {
    callback()
  }
}

const rules = reactive({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '5-10个数字或字母组合', trigger: 'blur' }
  ],
  birthDay: [
    {
      required: true,
      message: '请输入出生日期'
    }
  ],
  sex: [
    {
      required: true,
      message: '请选择性别'
    }
  ],
  telephone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 10, message: '5-10个字符', trigger: 'blur' }
  ],
  checkPass: [{ validator: validatePass2, required: true, trigger: 'blur' }]
})

const form = ref({})

const props = {
  identifyCode: '1234',
  fontSizeMin: 25,
  fontSizeMax: 35,
  backgroundColorMin: 200,
  backgroundColorMax: 220,
  dotColorMin: 60,
  dotColorMax: 120,
  contentWidth: 100,
  contentHeight: 40
}

const randomNum = (min, max) => {
  return Math.floor(Math.random() * (max - min) + min)
}

const randomColor = (min, max) => {
  let r = randomNum(min, max)
  let g = randomNum(min, max)
  let b = randomNum(min, max)
  return 'rgb(' + r + ',' + g + ',' + b + ')'
}

const drawPic = () => {
  let canvas = document.getElementById('id-canvas')
  let ctx = canvas.getContext('2d')
  ctx.textBaseline = 'bottom'
  ctx.fillStyle = '#e6ecfd'
  ctx.fillRect(0, 0, props.contentWidth, props.contentHeight)
  for (let i = 0; i < props.identifyCode.length; i++) {
    drawText(ctx, props.identifyCode[i], i)
  }
  drawLine(ctx)
  drawDot(ctx)
}

const drawText = (ctx, txt, i) => {
  ctx.fillStyle = randomColor(50, 160)
  ctx.font = randomNum(props.fontSizeMin, props.fontSizeMax) + 'px SimHei'
  let x = (i + 1) * (props.contentWidth / (props.identifyCode.length + 1))
  let y = randomNum(props.fontSizeMax, props.contentHeight - 5)
  const deg = randomNum(-30, 30)
  ctx.translate(x, y)
  ctx.rotate((deg * Math.PI) / 180)
  ctx.fillText(txt, 0, 0)
  ctx.rotate((-deg * Math.PI) / 180)
  ctx.translate(-x, -y)
}

const drawLine = (ctx) => {
  for (let i = 0; i < 4; i++) {
    ctx.strokeStyle = randomColor(100, 200)
    ctx.beginPath()
    ctx.moveTo(randomNum(0, props.contentWidth), randomNum(0, props.contentHeight))
    ctx.lineTo(randomNum(0, props.contentWidth), randomNum(0, props.contentHeight))
    ctx.stroke()
  }
}

const drawDot = (ctx) => {
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = randomColor(0, 255)
    ctx.beginPath()
    ctx.arc(randomNum(0, props.contentWidth), randomNum(0, props.contentHeight), 1, 0, 2 * Math.PI)
    ctx.fill()
  }
}

onMounted(async () => {
  await getIdentifyCode()
  drawPic()
})

const getIdentifyCode = async () => {
  const response = await $axios.get(`/api/admin/getVerifyCode`)
  props.identifyCode = response.data.data.verifyCode
  form.value.sessionId = response.data.data.sessionId
}

const refreshCaptcha = async () => {
  await getIdentifyCode()
  drawPic()
}

watch(
  () => props.identifyCode,
  (val) => {
    console.log(val)
    drawPic()
  }
)

const countdown = ref(5) // 倒计时秒数，默认为 5
let timer // 定时器
const onSubmit = async (formEl) => {
  if (!formEl) return
  // 在提交数据之前对所有的数据进行一次统一的验证
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 所以的数据已经通过验证
      console.log(form.value)
      const path = '/api/admin/register'

      // 发送注册请求
      const response = await $axios.post(path, form.value)
      console.log(form.value)
      const res = response.data

      if (res.code === '00000') {
        // 倒计时逻辑
        countdown.value = 5 // 重置倒计时秒数
        timer = setInterval(() => {
          if (countdown.value > 1) {
            countdown.value--
          } else {
            clearInterval(timer)
            router.push('/')
          }
        }, 1000)
        ElMessage({
          showClose: true,
          message: `注册成功，${countdown.value}秒后跳转到登录页面。`,
          type: 'success'
        })
      } else if (res.code === 'A0101') {
        ElMessage({
          showClose: true,
          message: '注册失败！',
          type: 'error'
        })
      } else if (res.code === 'A0104') {
        ElMessage({
          showClose: true,
          message: '用户名已被注册！',
          type: 'error'
        })
      } else if (res.code === 'A0105') {
        ElMessage({
          showClose: true,
          message: '手机号已被注册!',
          type: 'error'
        })
      } else if (res.code === 'A0240') {
        ElMessage({
          showClose: true,
          message: '验证码错误!',
          type: 'error'
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 在组件销毁或离开时清除 timer
onBeforeUnmount(() => {
  clearInterval(timer)
})

const resetForm = (formEl) => {
  formEl.resetFields()
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style lang="scss" scoped>
#container {
  display: flex;
  width: 100%;
  height: 150%;

  #header {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 10%;

    .logo {
      position: absolute;
      top: 45%;
      left: 200px;
      transform: translate(-50%, -50%);

      img {
        width: 70%;
        height: 70%;
        margin-top: 10px;
      }
    }

    .title {
      position: absolute;
      display: flex;
      margin-left: 230px;
      align-items: center;
      height: 100%;
      width: 100%;
      font-size: 25px;
      color: black;
    }

    .link {
      position: absolute;
      display: flex;
      align-items: center;
      margin-left: 1400px;
      margin-top: 25px;

      .plain-button {
        background-color: transparent;
        font-size: 16px;
      }
    }
  }

  #body {
    position: absolute;
    margin-top: 75px;
    height: 90%;
    width: 100%;
    background-size: 100%;
    background-repeat: no-repeat;
    background-position-x: center;
    background-image: url('../assets/img/wetlands.png');

    .box-card {
      width: 600px;
      margin: 0 auto;
      margin-top: 25px;
      overflow: hidden;
      border: 1px solid #b3e19d;
      border-top-left-radius: 7px;
      border-top-right-radius: 7px;
      font-size: 13px;

      .card-header {
        display: flex;

        .info {
          width: 100%;
          font-size: 20px;
          color: rgb(196, 220, 114);
        }
      }

      .registerwin {
        margin-left: 20px;
        padding: 20px;
        line-height: 35px;

        .touxiang {
          position: absolute;

          .avatar-uploader {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 120px;
            height: 120px;
            border-radius: 50%;
            border: 1px dashed #d9d9d9;
            overflow: hidden;
            position: relative;
            cursor: pointer;
            margin-left: 50px;

            .avatar {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }

            .el-icon.avatar-uploader-icon {
              font-size: 28px;
              color: #8c939d;
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
            }
          }
        }

        .registerform {
          .input {
            width: 300px;
          }

          .small-input {
            width: 180px;
          }
        }

        .captcha-container {
          display: flex;
          align-items: center;

          .input {
            flex: 1;
          }

          .canvas-box {
            margin-left: 10px;
            cursor: pointer;

            .id-canvas {
              height: 40px;
              width: 100px;
            }
          }
        }
      }
    }
  }

  #footer {
    position: absolute;
    margin-top: 100px;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 20%;

    .imgFooter {
      position: relative;
      margin-top: 30px;
      display: flex;
      width: 100%;
      height: 300%;
    }
  }
}

.demo-date-picker .block {
  padding: 10px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}
</style>
